﻿//01矩阵(medium): https://leetcode.cn/problems/01-matrix/
class Solution {
public:
    vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {
        int m=mat.size(),n=mat[0].size();
        vector<vector<int>> vis(m,vector<int>(n));
        vector<vector<int>> ret(m,vector<int>(n));
        queue<pair<int,int>> q;
        for(int i=0;i<m;i++)
        {
            for(int j=0;j<n;j++)
            {
                if(mat[i][j]==0)  
                {
                    q.push({i,j});
                    vis[i][j]=true;
                } 
            }
        }
        int dx[4] = {0, 0, 1, -1};
        int dy[4] = {1, -1, 0, 0};
        int step=0;
        while(q.size())
        {
            step++;
            int LeverSize=q.size();
            while(LeverSize--)
            {
                auto [a,b]=q.front();
                q.pop();
                for(int i=0;i<4;i++)
                {
                    int x=a+dx[i],y=b+dy[i];
                    if(x>=0&&x<m&&y>=0&&y<n&&!vis[x][y])
                    {
                        if(mat[x][y]==1)   
                        {
                            ret[x][y]=step;
                        }
                        vis[x][y]=true;
                        q.push({x,y});
                    }
                }
            }
        }
        return ret;
    }
};

//飞地的数量(medium): https://leetcode.cn/problems/number-of-enclaves/description/
class Solution {
public:
    int dx[4] = {0, 0, 1, -1};
    int dy[4] = {1, -1, 0, 0};
    int numEnclaves(vector<vector<int>>& grid) {
        int m=grid.size(),n=grid[0].size();
        queue<pair<int,int>> q;
        for(int i=0;i<m;i++)
        {
            if(grid[i][0]==1)
            {
                q.push({i,0});
                grid[i][0]=-1;
            }
            if(grid[i][n-1]==1)
            {
                q.push({i,n-1});
                grid[i][n-1]=-1;
            }
        }
        for(int j=0;j<n;j++)
        {
            if(grid[0][j]==1)
            {
                q.push({0,j});
                grid[0][j]=-1;
            }
            if(grid[m-1][j]==1)
            {
                q.push({m-1,j});
                grid[m-1][j]=-1;
            }
        }
        while(q.size())
        {
            auto [a,b]=q.front();
            q.pop();
            for(int i=0;i<4;i++)
            {
                int x=a+dx[i],y=b+dy[i];
                if(x>=0&&x<m&&y>=0&&y<n&&grid[x][y]==1)
                {
                    grid[x][y]=-1;
                    q.push({x,y});
                }
            }
        }
        int ret=0;
        for(int i=0;i<m;i++)
        {
            for(int j=0;j<n;j++)
            {
                if(grid[i][j]==1)   ret++;
                else if(grid[i][j]==-1)  grid[i][j]=1;
            }
        }
        return ret;
    }
};